/**
* @classDescription 微信公众平台消息推送来的xml解析工具
* @author laiwp
* @createDate 2016-06-11
* @version 0.1.2
* 微信返回数据格式如下:
<xml><return_code><![CDATA[SUCCESS]]></return_code>
<return_msg><![CDATA[OK]]></return_msg>
<appid><![CDATA[wxf975507c0382a092]]></appid>
<mch_id><![CDATA[10035161]]></mch_id>
<nonce_str><![CDATA[QPKt0TXbAoyrnK9w]]></nonce_str>
<sign><![CDATA[E511536E420B750B8C29E9D402D45FF9]]></sign>
<result_code><![CDATA[SUCCESS]]></result_code>
<prepay_id><![CDATA[wx20141212171904515c60510c0967152507]]></prepay_id>
<trade_type><![CDATA[JSAPI]]></trade_type>
</xml>

*/

var sax = require("sax");
var parser = sax.parser(strict, {
    lowercasetags: true,
    trim: true
}),
strict = true;

var dt = new Array();
var dts = new Array();
var st = '';
//var ToUserName, FromUserName, CreateTime, MsgType, Content, MsgId;
var wxMsg;

exports.pars = function(xmlcode, cb) {
    parser.write(xmlcode).close();
    //cb(ToUserName, FromUserName, CreateTime, MsgType, Content, MsgId);
    cb(wxMsg);
};
parser.onerror = function(e) {
    // an error happened.
    console.log('error');
};
parser.ontext = function(t) {
    // if(nm == 'billingtype' || nm == 'introduction')
    // st += '"' + nm +'":"' + t +'"';
    // else st += '"' + nm +'":"' + t +'",';
    st += '"' + nm + '":"' + t + '",';
};
parser.onready = function(a) {
    //console.log('aaaaaaaaaa:' + nm+"----> "+t);	
};

parser.onopentag = function(tag) {
    nm = tag.name;
    //console.log('xml 字段:' + nm);
    if (nm == 'xml') st = '{';
};
parser.onclosetag = function(tag) {
    if (tag == 'xml') {
        st += '}';
        //console.log('文件解析onclosetag完成!!!' + st.substring(st.length-2,st.length-1));
        if (st.substring(st.length - 2, st.length - 1) == ',') {
            var k = st.lastIndexOf(',');
            var str = st.substring(0, k);
            st = str + '}';
        }
        //if(tag == 'mercname')
        console.log('文件解析onclosetag完成0!!!' + st);
        dt.push(JSON.parse(st));
        st = '';
    };
};
parser.oncdata = function(data) {
	//sys.print("<![CDATA["+data+"]]>");
	st += '"' + nm + '":"' + data + '",';
};
parser.oncomment = function(comment) {
    console.log('文件解析oncomment完成!!!');
    //sys.print("<!--"+comment+"-->");
};
parser.onend = function() {
    console.log('文件解析onend完成!!!dt.length=' + dt.length);
    for (var i = 0; i < dt.length; i++) {
		wxMsg = {
	    	"prepay_id":dt[i].prepay_id,
	    	"result_code":dt[i].result_code,
	    	"sign":dt[i].sign,
	    	"return_code":dt[i].return_code,
	    	"return_msg":dt[i].return_msg,
	    	"nonce_str":dt[i].nonce_str,
	    	"trade_type":dt[i].trade_type
		};	
    };

};